'use strict';

const path = require('path');
const Package = require('@gok-cli/package');
const log = require('@gok-cli/log');
const { exec:spawn } = require('@gok-cli/utils');

const SETTINGS = {
    init: '@gok-cli/init'
}

const CATCH_DIR = 'dependencies';

async function exec() { // 获取arguments获取参数
    
    let targetPath = process.env.CLI_TARGET_PATH;
    const homePath = process.env.CLI_HOME_PATH;
    let storeDir = '', pkg;
    log.verbose('targetPath', targetPath);
    log.verbose('homePath', homePath);

    const commandArgs = arguments[arguments.length - 1];
    const cmdName = commandArgs.name();
    const pkgName = SETTINGS[cmdName];
    const pkgVersion = 'latest';

    if (!targetPath) {
        targetPath = path.resolve(homePath, CATCH_DIR);
        storeDir = path.resolve(targetPath, 'node_modules');
        log.verbose('targetPath', targetPath);
        log.verbose('storeDir', storeDir);
        pkg = new Package({
            targetPath,
            storeDir,
            pkgName,
            pkgVersion,
        });
        if (await pkg.exists()) {
            // 更新
            await pkg.update();
        } else {
            // 安装
            await pkg.install();
        }
    } else {
        pkg = new Package({
            targetPath,
            pkgName,
            pkgVersion,
        });
    }
    const rootFile = pkg.getRootFilePath();
    if (rootFile) {
        try {
            const args = Array.from(arguments);
            const cmd = args[args.length - 1];
            const o = Object.create(null);
            Object.keys(cmd).forEach(key => {
                if (cmd.hasOwnProperty(key) &&
                    !key.startsWith('_') &&
                key !== 'parent') {
                    o[key] = cmd[key] // 参数格式化
                }
            })
            args[args.length - 1] = o;
            const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`;
            const child = spawn('node', ['-e', code], {
                cwd: process.cwd(),
                stdio: 'inherit'
            });

            child.on('error', e => {
                log.error(e.message);
                process.exit(1)
            })

            child.on('exit', e => {
                log.verbose('命令执行成功：' + e)
            })

        } catch (e) {
            log.error(e.message);
        }
    }
    
}

module.exports = exec;